<template>
  <div id="system-role">
    <el-container style="overflow-x:hidden;overflow-y:hidden; height:100%;">
      <el-scrollbar
        style="width:100%;height:100%;white-space: nowrap;"
        @mousewheel.native="wheel"
        ref="roleRoll"
        class="roleRoll"
      >
        <el-header>
          <!-- 查询开始 -->
          <el-form
            :inline="true"
            :model="formInline"
            class="demo-form-inline"
            style="margin-top:20px"
          >
            <el-form-item>
              <el-input v-model="formInline.name" placeholder="角色"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                @click="onSubmit()"
                icon="el-icon-search"
                clearable
                v-permission="'admin:role:list'"
                >查询</el-button
              >
              <el-button
                type="primary"
                icon="el-icon-edit"
                @click="handleEdit(1)"
                v-permission="'admin:role:create'"
                >添加</el-button
              >
            </el-form-item>
          </el-form>
          <!-- 查询结束 -->
        </el-header>

        <el-main>
          <el-table
            :data="tableData"
            style="width: 100%;"
            :default-sort="{ prop: 'date', order: 'descending' }"
            align="center border show-summary"
            border
          >
            <!-- 角色列表数据 -->
            <el-table-column prop="name" label="姓名" sortable>
            </el-table-column>
            <el-table-column prop="desc" label="说明"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="primary"
                  @click="handleEdit(2, scope.$index, scope.row)"
                  v-permission="'admin:role:update'"
                  >编辑</el-button
                >
                <el-button
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index, scope.row)"
                  v-permission="'admin:role:delete'"
                  >删除</el-button
                >
                <el-button
                  size="mini"
                  type="primary"
                  @click="authorization(scope.$index, scope.row)"
                  v-permission="'admin:role:permissionList'"
                  >授权</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-main>
        <el-footer>
          <!-- 底部页数 -->
          <paging :paging="paging" :onSubmit="onSubmit"></paging>
        </el-footer>
      </el-scrollbar>
      <!-- 滚动组件结束 -->
    </el-container>
    <!-- 主要内容结束 -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible" center>
      <!-- 对话框表单 -->
      <el-form
        :model="ruleForm"
        status-icon
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        style="width:85%"
      >
        <el-form-item label="角色" prop="name">
          <el-input v-model="ruleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="说明" prop="desc">
          <el-input v-model="ruleForm.desc"></el-input>
        </el-form-item>
        <el-form-item style="text-align: center;">
          <el-button type="primary" @click="submitForm('ruleForm')"
            >确定</el-button
          >
          <el-button @click="dialogFormVisible = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="授权配置" :visible.sync="dialogVisible">
      <!-- 树形控件组件 -->
      <el-tree
        :data="data"
        show-checkbox
        node-key="id"
        ref="tree"
        :default-checked-keys="assignedPermissions"
        :props="defaultProps"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ node.label }}</span>
          <span v-if="data.api" class="el-tree_span">{{ data.api }}</span>
        </span>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="permissionSet()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import role from "@/api/role";
import Paging from "../../components/Paging";
export default {
  components: {
    Paging,
  },
  data() {
    var validateRole = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入角色"));
      } else {
        callback();
      }
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入说明"));
      } else {
        callback();
      }
    };
    return {
      formInline: {
        name: "", //角色查询
      },
      ruleForm: {
        //表单数据
        name: "",
        desc: "",
      },
      roledata: "", //选中的角色数据
      index: "", //选中的角色下标
      // modificationadta: "", //选中的角色数据修改
      rules: {
        //表单验证
        name: [{ required: true, validator: validateRole, trigger: "blur" }],
        desc: [{ required: true, validator: validatePass, trigger: "blur" }],
      },
      title: "创造", //对话框的名字
      dialogFormVisible: false, //对话框表单的隐藏显示
      dialogVisible: false, //对话框授权的隐藏显示
      tableData: [], //后台全部角色列表数据
      data: [], //授权数据
      assignedPermissions: [], //选中的数据
      defaultProps: {
        children: "children",
        label: "label",
      },
      paging: {
        currentPage: 1, //出现的页数
        pagesize: 10, //    每页的数据
        total: 0, //总条数
      },
    };
  },
  created: function() {
    //一开始的渲染数据
    let that = this;
    that.onSubmit();
  },
  methods: {
    onSubmit() {
      //查询
      let that = this;
      if (that.formInline.name != "") {
        //具体查询回到第一页，不然查询的数据在第一页，显示的页数和查询是页数不对
        that.paging.currentPage = 1;
      }
      let data = Object.assign(
        { page: that.paging.currentPage, limit: that.paging.pagesize },
        that.formInline
      );
      role
        .roleInquire(
          //角色查询接口封装
          data
        )
        .then((res) => {
          that.tableData = res.data.data.items; //获取数据赋值
          that.paging.total = res.data.data.total; //总条数
        })
        .catch(function(error) {
          console.log(error);
        });
    },
    handleEdit(digit, index, row) {
      //编辑和添加
      let that = this;
      this.dialogFormVisible = true;
      this.resetForm("ruleForm");
      if (digit == 1) {
        this.title = "创造";
        for (const i in that.ruleForm) {
          that.ruleForm[i] = "";
        }
      } else {
          //防止重置时没有数据
          setTimeout(function() {
          that.title = "编辑";
          that.roledata = row;
          that.index = index;
          for (const i in that.ruleForm) {
            that.ruleForm[i] = row[i];
          }
          }, 100);
      }
    },
    submitForm(formName) {
      //提交
      let that = this;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.dialogFormVisible = false;
          if (that.title == "创造") {
            //添加
            that.addition();
          } else {
            //编辑
            that.compile();
          }
        } else {
          return false;
        }
      });
    },
    addition() {
      //添加
      let that = this;
      role
        .roleAddition({
          //添加封装接口
          role: JSON.stringify(that.ruleForm),
        })
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.$message({
              type: "success",
              message: res.data.errmsg,
            });
            that.paging.total = that.paging.total + 1; //总共条数+1条
            that.onSubmit();
            that.tableData.push(res.data.data);
          } else {
            that.$message({
              message: res.data.errmsg,
              type: "warning",
            });
          }
        });
    },
    compile() {
      //编制
      let that = this;
      let data = Object.assign({ id: that.roledata.id }, that.ruleForm);
      role
        .roleCompile({
          //编制封装接口
          role: JSON.stringify(data),
        })
        .then(function(res) {
          if (res.data.errmsg == "成功") {
            that.$message({
              type: "success",
              message: res.data.errmsg,
            });
             for (let j in that.ruleForm) {
               that.tableData[that.index][j] = that.ruleForm[j];
             }
          } else {
            that.$message({
              message: res.data.errmsg,
              type: "warning",
            });
          }
        });
    },
    resetForm(formName) {
      //重置验证
      let that = this;
      setTimeout(function() {
        that.$refs[formName].resetFields();
      }, 100);
    },
    handleDelete(index, row) {
      //删除
      console.log(row);
      let that = this;
      this.$confirm("此操作将永久删除--" + row.name + "--, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          role
            .roleDelete({
              //删除封装接口
              roleId: row.id,
            })
            .then(function(res) {
              if (res.data.errmsg == "成功") {
                that.$message({
                  type: "success",
                  message: res.data.errmsg,
                });
                that.paging.total = that.paging.total - 1; //总共条数-1条
                that.tableData.splice(index, 1);
              } else {
                that.$message({
                  showClose: true,
                  message: res.data.errmsg,
                  type: "error",
                });
              }
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    authorization(index, row) {
      //授权
      console.log(index, row);
      this.roledata = row;
      let that = this;
      this.dialogVisible = true;
      role
        .roleshouqvan({
          //授权封装接口
          roleId: row.id,
        })
        .then(function(res) {
          that.data = res.data.data.systemPermissions; //全部数据
          that.assignedPermissions = res.data.data.assignedPermissions; //选中的数据id
        });
    },
    permissionSet() {
      //修改授权
      let that = this;
      this.dialogVisible = false;
      role
        .rolexgshouqvan({
          //修改授权封装接口
          roleSetPermissionDTO: JSON.stringify({
            roleId: that.roledata.id,
            permissions: that.$refs.tree.getCheckedKeys(),
          }),
        })
        .then(function(res) {
          //系统消息
          that.$notify({
            title: "成功",
            message: "这是一条成功的提示消息",
            type: "success",
          });
          that.data = res.data.data.systemPermissions; //全部数据
          that.assignedPermissions = res.data.data.assignedPermissions; //选中的数据id
        });
    },
    wheel(e) {
      //滚动事件
      e = e || window.event;
      if (e.wheelDelta) {
        if (e.wheelDelta < 0) {
          //控制滚动的方向
          //向下
          this.$refs.roleRoll.wrap.scrollTop += 20;
        } else {
          this.$refs.roleRoll.wrap.scrollTop -= 20;
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#system-role {
  //内容填满
  height: 100%;
}
.el-main {
  line-height: 0px !important;
}
.concer-input {
  //角色查询文本框
  width: 25%;
  margin-right: 10px;
}
.el-header {
  //查询布局
  line-height: 52px;
  height: auto !important;
}
.demo-form-inline {
  //查询布局
  white-space: pre-line;
}
.demo-form-inline > div {
  //查询布局
  margin-bottom: 0px;
}
</style>

<style>
.el-dialog__header,
.dialog-footer,
.el-tree-node__label,
.el-dialog__footer,
.el-checkbox,
.custom-tree-node {
  /*对话框的行高*/
  line-height: 0px;
}
.cell {
  /*角色列表居中*/
  text-align: center;
}
::-webkit-scrollbar {
  /*对话框的隐藏滚动条但是可以滚动，滚动条的宽度*/
  width: 0px !important;
}
</style>
